#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib
import simplejson as json
import os, sys, re, time, urllib2, dbus

class MPRIS:
    def __init__(self):
        self.bus = dbus.SessionBus()
        self.org_mpris_re = re.compile('^org\.mpris\.([^.]+)$')
        
        #self.player_name = os.environ.get('MPRIS_REMOTE_PLAYER', '*')
        
    def possible_names(self):
        return [ name for name in self.bus.list_names() if self.org_mpris_re.match(name) ]
    
    def get_player(self):
        names = self.possible_names()
        if not names:
            return False
        return self.org_mpris_re.match(names[0]).group(1)
      
    def get_meta(self):
        #if self.player_name == '*':
        if self.get_player():
            self.player_name = self.get_player()
        else:
            return 'No MPRIS-compliant player found running.'
            
        self.player_obj = self.bus.get_object('org.mpris.%s' % self.player_name, '/Player')        
        self.player = dbus.Interface(self.player_obj, dbus_interface='org.freedesktop.MediaPlayer')
        meta = dict(self.player.GetMetadata())
        artist = meta['artist']
        title = meta['title']
        album = meta['album']
        
        return artist, title, album

class YoutubeAPI:
    def __init__(self):
        self.encoder = urllib.urlencode
        self.parameters = {}
        self.parameters['alt'] = 'json'
        self.parameters['max-results'] = 1
        self.parameters['orderby'] = 'viewCount'
        
    def search(self, searchKW):
        self.parameters['vq'] = searchKW
        fp = urllib.urlopen('http://gdata.youtube.com/feeds/api/videos?%s' % self.encoder(self.parameters))
        try:
            return json.loads(fp.read())['feed']['entry'][0]['media$group']['media$player'][0]['url']
        except KeyError:
            return